package com.ruoyi.business.service.impl;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import com.ruoyi.business.constant.JtUserConstants;
import com.ruoyi.business.exception.BusinessException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.AliSendMessageUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.JtSmsLogMapper;
import com.ruoyi.business.domain.JtSmsLog;
import com.ruoyi.business.service.IJtSmsLogService;
import com.ruoyi.common.core.text.Convert;

import javax.validation.constraints.NotEmpty;

/**
 * 短信记录Service业务层处理
 * 
 * @author Alan Zhang
 * @date 2025-03-31
 */
@Service
public class JtSmsLogServiceImpl implements IJtSmsLogService 
{
    @Autowired
    private JtSmsLogMapper jtSmsLogMapper;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询短信记录
     * 
     * @param smsId 短信记录主键
     * @return 短信记录
     */
    @Override
    public JtSmsLog selectJtSmsLogBySmsId(Long smsId)
    {
        return jtSmsLogMapper.selectJtSmsLogBySmsId(smsId);
    }

    /**
     * 查询短信记录列表
     * 
     * @param jtSmsLog 短信记录
     * @return 短信记录
     */
    @Override
    public List<JtSmsLog> selectJtSmsLogList(JtSmsLog jtSmsLog)
    {
        return jtSmsLogMapper.selectJtSmsLogList(jtSmsLog);
    }

    /**
     * 新增短信记录
     * 
     * @param jtSmsLog 短信记录
     * @return 结果
     */
    @Override
    public int insertJtSmsLog(JtSmsLog jtSmsLog)
    {
        return jtSmsLogMapper.insertJtSmsLog(jtSmsLog);
    }

    /**
     * 修改短信记录
     * 
     * @param jtSmsLog 短信记录
     * @return 结果
     */
    @Override
    public int updateJtSmsLog(JtSmsLog jtSmsLog)
    {
        return jtSmsLogMapper.updateJtSmsLog(jtSmsLog);
    }

    /**
     * 批量删除短信记录
     * 
     * @param smsIds 需要删除的短信记录主键
     * @return 结果
     */
    @Override
    public int deleteJtSmsLogBySmsIds(String smsIds)
    {
        return jtSmsLogMapper.deleteJtSmsLogBySmsIds(Convert.toStrArray(smsIds));
    }

    /**
     * 删除短信记录信息
     * 
     * @param smsId 短信记录主键
     * @return 结果
     */
    @Override
    public int deleteJtSmsLogBySmsId(Long smsId)
    {
        return jtSmsLogMapper.deleteJtSmsLogBySmsId(smsId);
    }


    /**
     * 发送短信码
     * @param countyCode 国家码
     * @param phoneNumber  手机号
     * @param type 短信类型  1 注册  2 验证
     * @return
     */
    public AjaxResult sendSms(@NotEmpty Integer countyCode, @NotEmpty String phoneNumber, @NotEmpty int type) throws Exception {
        JtSmsLog param =  new JtSmsLog();
        param.setPhoneNumber(phoneNumber);
        param.setCountryCode(countyCode);
        param.setStatus(1);
        param.setType(type);
        List<JtSmsLog> list = selectJtSmsLogList(param);
        if(list.size() > 0){
            JtSmsLog jtSmsLog = list.get(0);

            long diff = System.currentTimeMillis() - jtSmsLog.getSendDate().getTime();
            if(diff < 2 *60 * 1000){
                return AjaxResult.error("操作太频繁，请稍后再试！");
            }
        }
        String code = randomInt() + "";
        String resMsg = "";
        String sendVal = configService.selectConfigByKey("sys.send.message");
        if("1".equals(sendVal)) {
            if (JtUserConstants.SMS_SIGN_UP_STATUS == type) {
                if(86 == countyCode) {
                    resMsg = AliSendMessageUtil.signUpSendMessage(countyCode + phoneNumber, code);
                } else {
                    resMsg = AliSendMessageUtil.signUpSendMessageToGlobe(countyCode + phoneNumber, code);
                }
            } else {
                if(86 == countyCode) {
                    resMsg = AliSendMessageUtil.signInSendMessage(countyCode + phoneNumber, code);
                } else {
                    resMsg = AliSendMessageUtil.signInSendMessageToGlobe(countyCode + phoneNumber, code);
                }
            }
        }
        JtSmsLog jtSmsLog = new JtSmsLog();
        jtSmsLog.setSendDate(new Date());
        jtSmsLog.setPhoneNumber(param.getPhoneNumber());
        jtSmsLog.setCountryCode(param.getCountryCode());
        jtSmsLog.setSmsCode(code);
        jtSmsLog.setStatus(1);
        jtSmsLog.setResponseCode(resMsg);
        jtSmsLog.setType(type);
        int rows = insertJtSmsLog(jtSmsLog);
        if(rows > 0) {
            return AjaxResult.success("发送成功！");
        } else {
            return AjaxResult.error("发送失败！");
        }
    }

    //随机6 位数字
    private int randomInt(){
        return (int)((Math.random()*9+1)*100000);
    }


    /**
     * 校验 短信码
     * @param phoneNumber 手机号
     * @param smsCode 短信码
     * @return
     */
    @Override
    public boolean validSmsCode(Integer countryCode, String phoneNumber, String smsCode, int type){
        if(countryCode == null || StringUtils.isEmpty(phoneNumber) || smsCode == null){
            return false;
        }
        JtSmsLog param = new JtSmsLog();
        param.setCountryCode(countryCode);
        param.setPhoneNumber(phoneNumber);
        param.setStatus(1);//有效
        param.setType(type);
        List<JtSmsLog> smsCodeList = selectJtSmsLogList(param);
        if(smsCodeList.size() > 0) {
            JtSmsLog jtSmsLogDb = smsCodeList.get(0);
            if(jtSmsLogDb.getSmsCode().equals(smsCode)) {
                JtSmsLog smsLog = new JtSmsLog();
                smsLog.setSmsId(jtSmsLogDb.getSmsId());
                smsLog.setStatus(0);//失效
                smsLog.setUpdateTime(DateUtils.getNowDate());
                updateJtSmsLog(smsLog);
                //短信二十分钟有效
                long d = DateUtils.getNowDate().getTime() - jtSmsLogDb.getCreateTime().getTime();
                if ((d / 1000 / 60) > 20) {
                    return false;
                }
                return true;
            }
        }
        return false;
    }
}
